const fs = require("fs");
const dir = require("../CONST");
const PORT = 8888;
const HOST = "http://localhost";
const HOSTNAME = `${HOST}:${PORT}`;
/**
 *
 * @param {} res
 * @param {string} path 路径
 * @param {*} file 文件
 * @param {*} filename 文件名
 * @param {*} stream 是否开启流式上传
 */
const writeFile = (res, path, file, filename, stream) => {
  return new Promise((resolve, reject) => {
    if (stream) {
      try {
        let readStream = fs.createReadStream(file.path);
        let writeStream = fs.createWriteStream(path);
        readStream.pipe(writeStream);
        readStream.on("end", () => {
          resolve();
          fs.unlinkSync(file.path);
          res.send({
            code: 200,
            message: "创建成功",
            filenamePath: `${HOSTNAME}/upload/${filename}`,
          });
        });
      } catch (error) {
        reject(err);
        res.send({
          code: -1,
          message: "创建文件失败",
        });
      }
    } else {
      fs.writeFile(path, file, (err) => {
        if (err) {
          reject(err);
          res.send({
            code: -1,
            message: "创建文件失败",
          });
        } else {
          resolve();
          res.send({
            code: 200,
            message: "创建成功",
            filePath: `${HOSTNAME}/upload/${filename}`,
          });
        }
      });
    }
  });
};

module.exports = writeFile;
